package com.framework.boc.admin.pay.utils;

import com.bocnet.common.security.PKCS7Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

public class BocPaySignTool {

    private static Logger logger = LoggerFactory.getLogger(BocPaySignTool.class);

    /**
     * 加签
     * @param plainData     源数据
     * @param pfxName       证书名称
     * @param keyPwd        证书密码
     * @return              加签后数据
     * @throws Exception    加签异常
     */
    public static String sign(String plainData, String pfxName, String keyPwd) throws Exception {
        String signData ="";
        try {
            //2、加签
            String pfxPath = BocPaySignTool.class.getClassLoader().getResource(pfxName).getPath();
            //加签的证件和密码
            PKCS7Tool signer = PKCS7Tool.getSigner(pfxPath, keyPwd, keyPwd);
            signData = signer.sign(plainData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
        return signData;
    }


    /**
     * 验签
     * @param plainData     源数据
     * @param signData      加签后数据
     * @param cerName       验签证书名称
     * @return              验签结果
     */
    public static boolean verifySign(String plainData, String signData, String cerName) {
        try {
            byte[] data = plainData.getBytes("UTF-8");
            //验签
            String pfxPath = BocPaySignTool.class.getClassLoader().getResource(cerName).getPath();
            PKCS7Tool tool = PKCS7Tool.getVerifier(pfxPath);
            tool.verify(signData, data, null);
        } catch (GeneralSecurityException e) {
            logger.error(e.getMessage());
            return false;
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            return false;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        }
        logger.info("验签成功");
        return true;
    }


}
